class TreeNode {
  constructor(title, children = [], indentLevel = 0) {
    this.title = title;
    this.children = children;
    this.indentLevel = indentLevel;
    this.element = null;
  }

  render(parentElement) {
    const div = document.createElement("div");
    div.className = "tree-node";
    if (this.isHighlighted) div.classList.add("highlight");
    div.tabIndex = 0; // 使div可聚焦以触发鼠标悬停效果

    // 创建并添加indent
    for (let i = 0; i < this.indentLevel; i++) {
      const indentDiv = document.createElement("div");
      indentDiv.className = "indent";
      div.appendChild(indentDiv);
    }

    // 添加switcher
    const switcher = document.createElement("div");
    switcher.className = "switcher";
    switcher.addEventListener("click", () => this.toggleChildren());
    div.appendChild(switcher);

    // 添加checkbox
    const checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.addEventListener("click", () => this.toggleCheckbox());
    div.appendChild(checkbox);

    // 添加content
    const content = document.createElement("span");
    content.className = "content";
    content.textContent = this.title;
    content.addEventListener("click", () => this.onSelect());
    div.appendChild(content);

    // 递归渲染子节点
    if (this.children.length > 0) {
      const childrenDiv = document.createElement("div");
      this.children.forEach((child) => child.render(childrenDiv));
      div.appendChild(childrenDiv);
      this.childrenDiv = childrenDiv;
      this.switcherStatus = false; // 初始状态为关闭
      switcher.textContent = "+";
    }

    parentElement.appendChild(div);
    this.element = div;
  }

  toggleChildren() {
    if (this.childrenDiv) {
      if (!this.switcherStatus) {
        this.childrenDiv.style.display = "block";
        this.switcherStatus = true;
        this.element.querySelector(".switcher").textContent = "-";
      } else {
        this.childrenDiv.style.display = "none";
        this.switcherStatus = false;
        this.element.querySelector(".switcher").textContent = "+";
      }
    }
  }

  toggleCheckbox() {
    this.element.querySelector('input[type="checkbox"]').checked =
      !this.element.querySelector('input[type="checkbox"]').checked;
  }

  onSelect() {
    console.log(`Selected: ${this.title}`);
    // 这里可以触发onSelect事件，根据项目需求进行处理
  }

  highlight() {
    this.isHighlighted = true;
    if (this.element) this.element.classList.add("highlight");
  }

  unhighlight() {
    this.isHighlighted = false;
    if (this.element) this.element.classList.remove("highlight");
  }
}

// 示例使用
document.addEventListener("DOMContentLoaded", () => {
  const treeData = [
    new TreeNode("Node 1", [new TreeNode("Child 1"), new TreeNode("Child 2")]),
    new TreeNode("Node 2"),
  ];

  const treeContainer = document.getElementById("treeContainer");
  treeData.forEach((node) => node.render(treeContainer));

  // 可以添加事件监听器来处理鼠标悬停高亮等效果
});
